import React,{createRef} from 'react'
import echarts from 'echarts'
import {createGraphOption} from './js/createEchartsOptions'
import {Input, Form, Select, Button, Row, Col, Tag, message} from 'antd'
import moment from 'moment'
const {Option} = Select
const body = document.querySelector('body')
const offsetHeight = (body.offsetHeight).toString()+'px'




const UnSelected = 0

export default class Graph extends React.Component {
  constructor(props){
    super(props)
    this.graphWraperRef = createRef()
    this.echart = {}
    this.state = {
      graphData:props.graphData,
      collectorList:[{name:'请选择节点',id:UnSelected}],
      graphOption:{},
      seriesDataIndex:0,
      canCompile:true,
      initFormData:{},
      formData:{
        compiledCancleName:'',
        selectCurNodeId:null,
        selectChildNodeId:[],
      }
      
    }
   
  }


  initEchart = (dom) =>{
    this.echart = echarts.init(dom.current)
    this.echart.off('click')
    this.echart.on('click', this.handleEchartClick)
  }
  handleEchartClick = (params) => {

    const {name} = params

    const option = this.echart.getOption()

    

    option.series[0].data.forEach((item,index,serier_data) => { //改变option的itemstyle颜色
      option.series[0].data[index].itemStyle.color = '#1890ff'

      if(item.name === name){
        option.series[0].data[index].itemStyle.color = 'red'
        //保存被点击节点在seriers_dara中的索引
        this.setState({
          seriesDataIndex:index
        },() => {
          //保存被点击节点的子节点,和本身的节点id
          const {links} = option.series[0]
          const {seriesDataIndex, formData} = this.state
          let childrenNodesId = []
          links.forEach(link => {
            if(link.source === seriesDataIndex){//如果被点击节点的index===link的source,则获取target在seriers中的index
              const itemId = serier_data[link.target].info.id
              childrenNodesId.push(itemId)
            }
          })
          this.setState({
            formData:{
              ...formData,
              selectCurNodeId:item.info.id,
              selectChildNodeId:childrenNodesId
            }
          })
          
        })
      }
      if(item.info.head){ //首节点被点击不变色
        option.series[0].data[index].itemStyle.color = '#0aa679'
      }
      

    })
    this.echart.setOption(option,true)

    

    
  }

  componentDidMount(){
    this.initEchart(this.graphWraperRef) //初始化graph
  }

  //保存更改
  handleSaveCompile = () => {
    
  }

  //更改当前选中节点的名称
  handleSelectCurNode = (id) => {

    const {seriesDataIndex} = this.state
    const {formData} = this.state
    const option = this.echart.getOption()
    const {level} = option.series[0].data[seriesDataIndex].info
    const equativeNodes =  option.series[0].data.filter(item => item.level === level).map(item => item.id) //先找到需要改变名称的节点的所有同级节点,以id作为数组



    if(equativeNodes.includes(id)){
      message.error('同级含有相同节点，无效的修改！')
      return
    }else if(id === UnSelected){
      message.error('请选择节点！')
      return
    }


    
    this.setState({
      formData:{
        ...formData,
        selectCurNodeId:id
      }
    }, () => {
      this.changeEchartsViewByFormData()
    })
  }


  //为当前选中的节点添加子节点
  handleSelectChildNode = (id) => {
    if(id === UnSelected){
      message.error('请选择子节点！')
      return
    }
    const {formData} = this.state
    const {selectChildNodeId, selectCurNodeId} = formData
    const name = this.findCollectorByKey(id,'id').name

    if(id === selectCurNodeId){
      message.error('所选子节点与当前节点相同，无效子节点！')
      return
    }else if(selectChildNodeId.includes(id)){
      message.info(`当前节点已包含节点:${name},禁止重复添加!`)
      return
    }
    
    this.setState({
      formData:{
        ...formData,
        selectChildNodeId:selectChildNodeId.concat([id])
      }
    },() => {
      this.changeEchartsViewByFormData()
    })

  }
  changeEchartsViewByFormData = () =>{
    const {formData,seriesDataIndex} = this.state
    const {selectChildNodeId, selectCurNodeId} = formData
    const option = this.echart.getOption()
    const length = option.series[0].data.length
    const {level} = option.series[0].data[seriesDataIndex].info
    const series_data = option.series[0].data
    const series_links = option.series[0].links

  


    //设置当前节点名称
    const curNodeName = this.findCollectorByKey(selectCurNodeId,'id').name
    series_data[seriesDataIndex].name = `${curNodeName}[${level}级节点]`
    series_data[seriesDataIndex].info.id = selectCurNodeId
    //设置当前节点的子节点
    selectChildNodeId.map((id,index) => {
      const name = this.findCollectorByKey(id,'id').name
      return {
          name:`${name}[${level+1}级节点]`,
          symbolSize:100,
          info:{
            head:false,//非文档属性，自定义属性，表示节点是否为首节点
            id, //非文档属性，自定义属性，表示节点所处层级，用于节点去重
            level:level+1,
          },
          itemStyle:{
            color:'#1890ff'
          }
      }
    }).forEach(item => {
      const level = item.info.level
      const id = item.info.id
      const equalLevelNodes = series_data.filter(el => el.info.level === level).map(el => el.info.id)
      if(equalLevelNodes.includes(id)){
        return
      }else{
        series_data.push(item)
        series_links.push({source:seriesDataIndex,target:length})
      }
    })


    this.echart.setOption(option, true)
    

  }
  handleCancleNameChange = (value) => {
  }

  //删除子节点
  deleteTag = (removedTag) => {
    const {formData} = this.state
    const selectChildNodeId = this.state.formData.selectChildNodeId.filter(id => id!==removedTag)
    this.setState({
      formData:{
        ...formData,
        selectChildNodeId,
      }
    },() => {
      const removedId = removedTag
      const {selectChildNodeId} = this.state.formData
      const {seriesDataIndex} = this.state
      const option = this.echart.getOption()
      const series_data = option.series[0].data
      let series_links = option.series[0].links
      const relatedLinks = series_links.filter(link => link.source === seriesDataIndex)
      const removedLink = {source:'',target:''}
      for(let i =0;i<relatedLinks.length;i++){
        let {source, target} = relatedLinks[i]
        if(series_data[target].info.id === removedId){ //target即是removedId在series_data中的索引
          // series_data.splice(target,1)
          series_data[target].name = moment().valueOf()
          series_data[target].symbolSize = 0
          removedLink.source = source
          removedLink.target = target
          break
        }
      }
      
      series_links = series_links.map(({source, target}) => {
        if(source === removedLink.source && target === removedLink.target){
          return null
        }
        // if(source>removedLink.source && target>removedLink.target){
        //   return {source:source-1,target:target-1}
        // }
        // if(source>removedLink.source){
        //   return {source:source-1, target}
        // }
        // if(target>removedLink.target){
        //   return {source, target:target-1}
        // }
        return {source, target}

      }).filter(link => link)
      option.series[0].links = series_links
      option.series[0].data = series_data
      this.echart.setOption(option)

    })
  }
  closable = (id) =>{
    let closeable = true
    const option = this.echart.getOption()
    const series_data = option.series[0].data
    const series_links = option.series[0].links
    const relatedLinks = series_links.filter(link => link.source === this.state.seriesDataIndex)
    relatedLinks.forEach(link =>{
      const {target} = link
      if(series_data[target].info.id === id){ //target即是removedId在series_data中的索引
        const secondLinks = series_links.filter(el => el.source === target) //以target作为source的二级节点
        if(secondLinks.length){
          closeable = false
        }
      }
    })
    return closeable
  }
  cancelOrCompile = () => {
    const {canCompile} = this.state
    if(!canCompile){
      this.setState({
        formData:{
          ...this.state.initFormData
        }
      },() => {
        this.changeEchartsViewByFormData()
      })
    }
    this.setState({
      canCompile:!canCompile
    })
  }
  //根据id和name互相查找
  findCollectorByKey = (value, key) => {
    const {collectorList} = this.state
    return collectorList.find(item => item[key] === value)
  }
  

  componentWillReceiveProps(nextProps){
    const {collectorList} = this.state
    const {graphData:propsGraphData, collectorList:propsCollextorList} = nextProps
    this.setState({
      graphData:propsGraphData,
      collectorList:collectorList.concat(propsCollextorList),
    },() => {
      const {graphData} = this.state
      const option = createGraphOption(graphData)
      option.series[0].data.forEach((item,index) => {//默认初始化为首节点为被选中节点
        if(item.info.head){
          const childrenIndex = option.series[0].links.filter(link => {
            return link.source === index
          })
          const childrenId = childrenIndex.map(childIndex => option.series[0].data[childIndex.target].info.id)
          this.setState({
            seriesDataIndex:index,
            initFormData:{
              compiledCancleName:graphData.name,
              selectCurNodeId:item.info.id,
              selectChildNodeId:childrenId
            }
            
          },() => {
            this.setState({
              formData:{
                ...this.state.initFormData
              }
            })
          })
          
        }
      })

      this.setState({
        graphOption:option,
       
      },() => {
        const {graphOption} = this.state
        this.echart.setOption(graphOption)
      })
    })
  }
  render(){
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };


    const {collectorList, canCompile, formData} = this.state
    const {compiledCancleName, selectCurNodeId, selectChildNodeId} = formData
    return (
      <Row gutter={24} type='flex' >
        <Col span={18}>
          <div id='graphWraper' ref={this.graphWraperRef} style={{height:offsetHeight}}></div>
        </Col>
        <Col span={6}>
          <Form {...formItemLayout}>
            <Form.Item label='频道名称'>
              <Input placeholder={compiledCancleName}  onChange={this.handleCancleNameChange} disabled={canCompile} />
            </Form.Item>

            <Form.Item label='当前节点'>
              <Select disabled={canCompile} value={selectCurNodeId} onSelect={this.handleSelectCurNode}> 
                {
                  collectorList.map(item => {
                    return (<Option value={item.id} key={item.id}>{item.name}</Option>)
                  })
                }
              </Select>
            </Form.Item>

            <Form.Item label='添加子节点' >
              <Select disabled={canCompile||!selectCurNodeId} onChange={this.handleSelectChildNode} >
                {
                  collectorList.map(item => {
                    return (<Option value={item.id} key={item.id}>{item.name}</Option>)
                  })
                }
              </Select>
            </Form.Item>

            <Form.Item label='子节点'>
              {
                selectChildNodeId.map(id => {
                    const name = this.findCollectorByKey(id,'id') ? this.findCollectorByKey(id,'id').name : null
                    return <Tag key={id}  closable={this.closable(id)} onClose={() => {this.deleteTag(id)}}>{name}</Tag>
                })
              }
            </Form.Item>
              
          </Form>
         
          <Row type='flex' justify='center'>
                <Col>
            <Button type={canCompile?'primary':'danger'} disabled={formData.selectCurNodeId === null} onClick={this.cancelOrCompile} >{canCompile?'编辑':'取消'}</Button>
                </Col>
                <Col>
                  <Button type='primary' disabled={canCompile} onClick={this.handleSaveCompile}>保存</Button>
                </Col>
          </Row>
        </Col>
      </Row>
    )
  }
}

